package com.my.lock.v3;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by ZhongGang
 * at 2018/7/27 14:59
 */
public class App {
    private static final Logger LOGGER = LoggerFactory.getLogger(App.class);

    public static void main(String[] args) throws Exception {
        Semaphore semaphore = new Semaphore(5);

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        //其它耗时操作

                        try {
                            Thread.sleep(3 * 1000);
                        } catch (InterruptedException e) {
                            throw new UnsupportedOperationException("Not yet implemented!");
                        }
                    } finally {
                        semaphore.release();
                    }
                }
            });
            threads.add(thread);
            thread.start();
        }

        for (Thread thread : threads) {
            thread.join();
        }

        LOGGER.info("sempahore: {}, queues: {}", semaphore.getPermits(), semaphore.getWaiters().size());
    }
}
